<?php
/**
 * User: yuesir
 * Date: 2016/4/29
 * Time: 0:01
 * 通过迭代器实现数据库表的遍历
 */

namespace Lib;


class AllUsers implements \Iterator{
    protected $ids;
    protected $data;
    protected $index;

    public function __construct()
    {
        $db = Factory::getDatabase();
        $result = $db->query('SELECT `id` from user');
        $this->ids = $result->fetch_all(MYSQL_ASSOC);
    }

    public function rewind() {
        $this->index = 0;
    }

    public function current() {
        $user = isset($this->data[$this->index]['id']) ? $this->data[$this->index]['id'] : array();
        if(!$user) {
            $user = $this->data[$this->index]['id'] = new User($this->ids[$this->index]['id']);
        }
        return $user;
    }

    public function key() {
        return $this->index;
    }

    public function next() {
        $this->index ++;
    }

    public function valid() {
        return $this->index < count($this->ids);
    }
}